import sublime
import sublime_plugin
import os
import json

class PhpFunctionCompleteCommand(sublime_plugin.EventListener):
    def on_query_completions(self, view, prefix, locations):
        print('PhpFunctionComplete start {0}, {1}'.format(prefix, locations))

        self.settings = sublime.load_settings('PhpFunctionComplete.sublime-settings')
        # only works on specific file types
        fileName, fileExtension = os.path.splitext(view.file_name())
        if not fileExtension.lower() in self.settings.get('available_file_types'):
            return []
        word = prefix
        if (word.strip() == ''):
            return []

        funstr = sublime.load_resource(self.settings.get('function_path'))
        functionsC = json.loads(funstr)
        fchar = word[0].lower();
        functions = functionsC[fchar];
        items = functions.items()
        snippets = []
        for fun, val in items:
            if fun.find(word) >= 0:
                snippets += [(str(val['desc']), str(fun)+('' if val['d']==1 else '(${1:})'))]
        return snippets
